package com.dahuyou.nio.discard.server.client;

import io.netty.buffer.ByteBuf;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioDiscardClient {

    public static void main(String[] args) throws Exception {
        InetSocketAddress inetSocketAddress
                = new InetSocketAddress("127.0.0.1", 18899);
        // 1：获取通道
        SocketChannel socketChannel = SocketChannel.open(inetSocketAddress);
        // 2：切换成非阻塞
        socketChannel.configureBlocking(false);
        // 不断自旋，等待连接完成
        while (!socketChannel.finishConnect()) {}
        System.out.println("链接server成功");
        // 3：创建缓冲区，填充数据，并向通道写入数据
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("hello discard server".getBytes());
        // 转成读模式,开始读数据写出去
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
        System.out.println("向server写数据done");

        // 关了，释放资源，好习惯
        socketChannel.shutdownOutput();
        socketChannel.close();
    }
}
